<script src="/public/static/layui/layui.js"></script>
<script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.17.0.min.js"></script>
<script>
    /* 
        elem:upload上传按钮dom元素
        multiple:是否多选
        tokenUrl:oss授权验证接口地址
        client:oss方法 参数
        uploadElem:点击上传按钮dom元素
        chooseCallback:选择图片后的回调
        beforeUploadCallback:上传前的操作
        uploadSuccessCallback:上传成功的操作
        uploadErrorCallback:上传失败的操作
    */
    function uploadFile(params) {
        let { elem, uploadElem, chooseCallback, beforeUploadCallback, uploadSuccessCallback, uploadErrorCallback, multiple = false, ossUrl, accept, acceptMime } = params
        let oss = ossUrl ?? '/admin/material_ali_upload/sts';
        var layerMask;
        layui.use(['layer', 'element', 'form', 'upload'], function () {
            var upload = layui.upload, client, files;
            var init = new Promise((resolve, reject) => {
                // 请求oss sts临时授权接口
                $.ajax({
                    url: oss,
                    type: "post",
                    async: false,
                    success: function (res) {
                        client = new OSS({
                            accessKeyId: res.data.AccessKeyId,
                            accessKeySecret: res.data.AccessKeySecret,
                            stsToken: res.data.SecurityToken,
                            bucket: res.data.bucket,
                            region: res.data.region
                        })
                        resolve()
                    }
                });
            });
            init.then(() => {
                // 调用layui上传
                upload.render({
                    elem,
                    multiple,
                    accept,
                    acceptMime,
                    auto: false,
                    choose: function (obj) {
                        files = obj.pushFile();
                        chooseCallback ? chooseCallback() : '';//选择文件后的操作
                        allUpload()
                    }
                })
                // 如果有全部上传接口,调用上传接口
                if (uploadElem) {
                    $(uploadElem).click(function () {
                        allUpload()
                    })
                }
            });
            // 全部上传
            function allUpload() {
                let arrFiles = Object.values(files);
                let arrFilesIndex = Object.keys(files);
                layerMask = layer.load(1, {
                    shade: [0.4, '#000']
                });
                for (let i in arrFiles) {
                    uploadOssPut(arrFiles[i].name, arrFiles[i], arrFilesIndex[i], Object.values(files).length, i);
                }
            }
            // 上传文件到oss
            function uploadOssPut(name, file, fileIndex, allIndex, index) {
                beforeUploadCallback ? beforeUploadCallback() : '';//上传前的操作
                client.put(fileName(name), file).then(function (v) {
                    if (allIndex - 1 == index) {
                        layer.close(layerMask)
                    }
                    if (v.res.status === 200) { //上传成功
                        uploadSuccessCallback ? uploadSuccessCallback(v, name) : '';//上传成功的操作
                        delete files[fileIndex];
                        return false;
                    } else {
                        uploadErrorCallback ? uploadErrorCallback() : '';//上传失败的操作
                    }
                })
            }
        })
    }
    // 视频上传
    uploadFile({
        elem: '#video_btn',
        ossUrl: '/admin/material_ali_upload/sts',
        multiple: true,
        accept: 'video',
        acceptMime: 'video/*',
        uploadSuccessCallback: function (res, name) {
            getVideoBase64(res.url).then((url) => {
                let client;
                var init = new Promise((resolve, reject) => {
                    // 请求oss sts临时授权接口
                    $.ajax({
                        url: '/admin/material_ali_upload/sts',
                        type: "post",
                        async: false,
                        success: function (data) {
                            client = new OSS({
                                accessKeyId: data.data.AccessKeyId,
                                accessKeySecret: data.data.AccessKeySecret,
                                stsToken: data.data.SecurityToken,
                                bucket: data.data.bucket,
                                region: data.data.region
                            })
                            resolve()
                        }
                    });
                });
                init.then(() => {
                    client.put(fileName(name.split('.')[0]), dataURLtoFile(url)).then(function (v) {
                        if (v.res.status === 200) { //上传成功
                            $('.layui-upload-list').show()
                            $("#video_content").val($("#video_content").val() ? $("#video_content").val() + ',' + res.url : res.url);
                            $("#video_title").val($("#video_title").val() ? $("#video_title").val() + ',' + name.split('.')[0] : name.split('.')[0]);
                            $("#video_cover").val($("#video_cover").val() ? $("#video_cover").val() + ',' + v.url : v.url);
                            $('.layui-upload-list').append(`
                                <div class="imgBox">
                                    <i class="layui-icon layui-icon-close-fill" onclick='getUrl(this,"#video_content")'></i>   
                                    <video controls class="layui-upload-img" style="width: 200px;" src=${res.url} >
                                </div>
                            `)
                        }
                    })
                });

            })

        },
        uploadErrorCallback: function () {
            return layer.msg('上传失败');
        }
    })
    // 图片上传
    uploadFile({
        elem: '#img_btn',
        ossUrl: '/admin/material_ali_upload/sts',
        multiple: true,
        accept: 'image',
        acceptMime: 'image/*',
        uploadSuccessCallback: function (res) {
            $('.layui-upload-list').show()
            $("#image_content").val($("#image_content").val() ? $("#image_content").val() + ',' + res.url : res.url);
            $('.layui-upload-list').append(`
            <div class="imgBox">
                <i class="layui-icon layui-icon-close-fill" onclick='getUrl(this,"#image_content")'></i>   
                <img onclick="showimg(this)" class="layui-upload-img" style="width: 100px;" src=${res.url}>
            </div>
        `)
        },
        uploadErrorCallback: function () {
            return layer.msg('上传失败');
        }
    })
    // 音频上传
    uploadFile({
        elem: '#audio_btn',
        ossUrl: '/admin/material_ali_upload/sts',
        multiple: true,
        accept: 'audio',
        acceptMime: 'audio/*',
        uploadSuccessCallback: function (res, name) {
            $('.layui-upload-list').show()
            $("#audio_content").val($("#audio_content").val() ? $("#audio_content").val() + ',' + res.url : res.url);
            $("#audio_title").val($("#audio_title").val() ? $("#audio_title").val() + ',' + name.split('.')[0] : name.split('.')[0]);
            $('.layui-upload-list').append(`
            <div class="imgBox" style='width:100%'>
                <i class="layui-icon layui-icon-close-fill" onclick='getUrl(this,"#audio_content")'></i>   
                <audio controls onclick="showimg(this)" class="layui-upload-img" style="width: 100%;" src=${res.url}>
            </div>
        `)
        },
        uploadErrorCallback: function () {
            return layer.msg('上传失败');
        }
    })
    function getVideoBase64(url) {
        return new Promise(function (resolve, reject) {
            let dataURL = '';
            let video = document.createElement("video");
            let output = document.getElementById("output");
            video.setAttribute('crossorigin', 'anonymous'); //处理跨域
            video.setAttribute('src', url);
            video.setAttribute('width', 540);
            video.setAttribute('height', 960);
            video.setAttribute('controls', 'controls');
            video.currentTime = 2;  //视频时长，一定要设置，不然大概率白屏
            video.addEventListener('loadeddata', function (e) {
                let canvas = document.createElement("canvas"),
                    width = video.width, //canvas的尺寸和图片一样
                    height = video.height;
                canvas.width = width;
                canvas.height = height;
                canvas.getContext("2d").drawImage(video, 0, 0, width, height); //绘制canvas
                dataURL = canvas.toDataURL('image/png'); //转换为base64
                // let img = document.createElement("img");
                // img.src = canvas.toDataURL("image/png"); // 获取图片的url
                // output.appendChild(img);
                resolve(dataURL);
            });
        })
    }
    function dataURLtoFile(dataURI) {
        let binary = atob(dataURI.split(",")[1]);
        let array = [];
        for (let i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i));
        }
        return new Blob([new Uint8Array(array)], { type: 'image/png' });
    }

    //文件上传路径+文件名
    function fileName(name) {
        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let hour = date.getHours();
        let minute = date.getMinutes();
        let second = date.getSeconds();
        return `${year}-${month}-${day}/${hour}-${minute}-${second}-${name}`;
    }

    /**
     * 展示图片
     * @param   {t} this   点击的this
     */
    function showimg(t) {
        layer.open({
            type: 1,
            title: false,
            closeBtn: 1,
            skin: 'layui-layer-nobg', //没有背景色
            shadeClose: true,
            maxWidth: '800',
            content: '<img style="display: inline-block; width: 100%; height: 100%;" src="' + t.src + '">'
        });
    }
    // 获取图片路径
    function getUrl(v, className) {
        let url = ''
        $(v).parent().remove()
        $('.layui-upload-list').children().each(function (index, item) {
            url += $(item).children('img').attr('src') + ','
        })
        $(className).val(url)
    }
</script>